package com.unirn.clinicas;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.tads.clinicas.R;
import com.unirn.clinicas.banco.RepositorioConsulta;
import com.unirn.clinicas.listview.AdapterListView;
import com.unirn.clinicas.listview.ItemListView;
import com.unirn.clinicas.modelo.Consulta;
import com.unirn.clinicas.ws.ClientRest;

@SuppressLint("HandlerLeak")
public class ListarActivity extends Activity implements OnItemClickListener, Runnable {
	private AdapterListView adapterListView;
	private Button btSalvarHistorico;
	private ListView listView;
	private ProgressDialog progressDialog;
	
	private ArrayList<ItemListView> listInfoConsultas;
	private List<Consulta> listaConsultas;
	private String cpf;
	private RepositorioConsulta repositorioConsulta;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_listar);
		
		listView = (ListView) findViewById(R.id.tela_consulta_listView);
		listView.setOnItemClickListener(this);

		btSalvarHistorico = (Button) findViewById(R.id.btSalvarHistorico);
		btSalvarHistorico.setOnClickListener(btSalvarHistoricoListener);

		Intent intent = getIntent();
		Bundle paramConsulta = intent.getExtras();
		if(paramConsulta != null)
			cpf = paramConsulta.getString("cpf");

		progressDialog = ProgressDialog.show(ListarActivity.this, "Aguarde", "Processando...");
		
		Thread thread = new Thread(ListarActivity.this);
		thread.start();
	}
	
    @Override
    public void onPause(){
        super.onPause();
        if(repositorioConsulta != null)
        	repositorioConsulta.close();
    }

	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		Intent intent = new Intent(ListarActivity.this, BuscarConsultaCpfActivity.class);
		Bundle param = new Bundle();

		Consulta c = listaConsultas.get(arg2);

		param.putInt(Consulta.ID, c.getId()); //id da consulta no banco local
		param.putInt(Consulta.ID_CONSULTA, c.getId_consulta()); //id da consulta no servidor
		param.putString(Consulta.PACIENTE, c.getPaciente());
		param.putString(Consulta.DATA_CONSUTA, c.getDataConsulta());
		param.putString(Consulta.HORARIO_CONSULTA, c.getHoraConsulta());
		param.putString(Consulta.CLINICA, c.getClinica());
		param.putString(Consulta.STATUS_CONSULTA, c.getStatusConsulta());

		intent.putExtras(param);
		startActivity(intent);
	}

	private OnClickListener btSalvarHistoricoListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			exibirAlerta();
		}
	};

	@Override
	public void run() {
		ClientRest clienteRest = new ClientRest();
		int tipoClinica = -1;

		try {
			listaConsultas = clienteRest.getListaConsulta(cpf);
			listInfoConsultas = new ArrayList<ItemListView>();
			
			for (Consulta consulta : listaConsultas) {
				if (consulta.getClinica().equals("Psicologia"))
					tipoClinica = 1;
				else if (consulta.getClinica().equals("Fisioterapia"))
					tipoClinica = 2;
				

				ItemListView itens = new ItemListView(tipoClinica, 
						consulta.getClinica(),
						consulta.getDataConsulta() + " - " + 
						consulta.getHoraConsulta(),
						consulta.getStatusConsulta()
				);
				
				listInfoConsultas.add(itens);
			}

			adapterListView = new AdapterListView(this, listInfoConsultas);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		handler.sendEmptyMessage(0);
	}
	
	private void exibirAlerta() {	
		AlertDialog.Builder dialog = new AlertDialog.Builder(ListarActivity.this);
		dialog.setMessage("Ao salvar seu historico seus dados anteriores serão perdidos. \nDeseja continuar?");
		
		dialog.setPositiveButton("Sim", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface di, int arg) {	
				repositorioConsulta = new RepositorioConsulta(ListarActivity.this);
				int qtdExcluidas = repositorioConsulta.deletarTodos();
				int qtd = repositorioConsulta.salvarLista(listaConsultas);

				Toast.makeText(ListarActivity.this, 
						"Consultas salvas: " + qtd + 
						"\nConsultas excluidas: " + qtdExcluidas, 
						Toast.LENGTH_LONG).show();
			}
		});

		dialog.setNegativeButton("Não", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface di, int arg) {
				
			}
		});
		
		dialog.setTitle("Aviso");
		dialog.show();
	}
	
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			progressDialog.dismiss();
			listView.setAdapter(adapterListView);

			if(listView.getCount() == 0){
				Toast.makeText(ListarActivity.this, "Nenhuma consulta encontrada para este CPF.", Toast.LENGTH_LONG).show();
			} else if(listView.getCount() == 1){
				Toast.makeText(ListarActivity.this, listView.getCount() + " consulta encontrada", Toast.LENGTH_LONG).show();	
			} else {
				Toast.makeText(ListarActivity.this, listView.getCount() + " consultas encontradas", Toast.LENGTH_LONG).show();		
			}
		}
	};
}